package ace.j2se.l2;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class SerializeUser implements Serializable {
	/**
	 * serialVersionUID 序列化id，序列化的id与解序列化的id必须一致，要不然会出错
	 */
	private static final long serialVersionUID = 2L;
	private String name;
	private int age;

	public SerializeUser(String name, int age) {
		this.name = name;
		this.age = age;
	}

	/**
	 * @todo 将一个可以序列化的对象写入文件
	 * @param obj
	 *            要保存的对象
	 * @param fileName
	 *            目标文件
	 */
	public void writeToFile(Object obj, String fileName) {
		try {

			FileOutputStream fos = new FileOutputStream(fileName);
			ObjectOutputStream oos = new ObjectOutputStream(fos);
			oos.writeObject(obj);
			oos.flush();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public Object getObjFromFile(String fileName) {
		Object obj = null;
		try {
			FileInputStream fis = new FileInputStream(fileName);
			ObjectInputStream ois = new ObjectInputStream(fis);
			obj = ois.readObject();
			System.out.println("readOk");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return obj;
	}

	public static void main(String[] args) {
		// System.out.println(ClassLoader.getSystemResource(""));
		String fileName = "user.txt";
		SerializeUser user = new SerializeUser("utest", 22);
		// user.writeToFile(user, fileName);
		SerializeUser u = (SerializeUser) (user.getObjFromFile(fileName));
		if (u != null) {
			System.out.println("get user from file ok,and name is : " + u.name); // 输出对象名
		}
	}
}
